﻿# coding:utf-8
from datetime import datetime

from WebBase.settings import logger
from tools import DBUtil
from tools.httpUtil import mako_render

request = None

serialVersionUID = 1L

from apps.cm.CmProductInfo import CmProductInfo
formobj = CmProductInfo() #  #表单 对象
operator = "" #  #跳转控制
rows =""  #表格显示行数
page  = "" #表格当前第几页
product_id  = ""  #隐藏的唯一值

# 下拉处理
search_type = ""  #访问类型,1为单下拉可选值,2为联动控制
search_combo = ""   #下拉值的全局常量类型
search_value = ""   #联动控制时的父亲值
    
#保存方式
# date = Date #1,新建（需要保存创建日期）2,修改（不保存创建日期）

search_product_name = str()

#
# def getComoboValues(): #获取下拉值
#         if (SysTools.getInstance().isStrValue(search_type, "1")) {
#             String sql = "select t.product_id, t.product_name from cm_product_info t order by t.product_name"
#             try {
#                 logger.info(sql)
#                 FormInitValues init=new FormInitValues()
#                 List<HashMap<String, String>> list=DBUtil.getInstance().executeQuery(sql)
#
#                 /*for (HashMap<String, String> map : list) {
#                     String item_cn = map.get("product_name")
#                     String item_value = map.get("product_id")
#
#                      #init.addComboValue("search_product_id", item_cn, item_value)
#                 }*/
#
#                 SysTools.getInstance().printHtmlData(list)
#
#
#             } catch (Exception e) {
#                 e.printStackTrace()
#             }
#
#         } else if (SysTools.getInstance().isStrValue(search_type, "2")) {
#             String sql = "select t.item_cn,t.item_value from cm_dict t where t.dict_type='"
#                     + search_combo+ "' and is_enable=1 and parent_node='"
#                     + search_value + "' order by item_order"
#             try {
#                 logger.info(sql)
#                 List res = DBUtil.getInstance().executeQuery(sql)
#                 SysTools.getInstance().printHtmlData(res)
#             } catch (Exception e) {
#                 e.printStackTrace()
#             }
#         }

operator_dic = {"Q":"/cm/cmProductInfo_list.html",
            "A":"/cm/add.html",
            "U":"/cm/del.html",
            "D":"/cm/cgk.html"}

# 页面跳转控制
def execute():
    print operator
    page = operator_dic.get(operator)  if operator_dic.has_key(operator) else operator_dic.get('Q')
    return mako_render(request, page, {})



def getUserList():
    pass



#      #页面初始化
#     public void getInitValue() throws SQLException{
#          #1.只读 2.默认值 3.下拉可选值
#         FormInitValues init=new FormInitValues()
#          #init.addReadonly("nn1").addReadonly("nn2").addReadonly("endtime")
#          #init.addDefaultValue("nn3", 1).addDefaultValue("starttime", new Date())
#          #.addDefaultValue("xlmrvalue1", 2).addDefaultValue("xlmrvalue2", "4")
#          #init.addComboValue("xlmrvalue1", "item_cn1", "1").addComboValue("xlmrvalue1", "item_cn2", "2")
#          #DictUtil.getKeyValueList("xlmrvalue1", "cm_customer.user_level", init)
#          #DictUtil.getKeyValueListWithSql("search_oprMenuId", "select fun_enname item_value,fun_cnname item_cn from sm_function where useable=1 order by fun_id", init)
#
#          #产品状态-CN
#         String datasql = "select t.item_cn, t.item_value from CM_DICT t where t.DICT_TYPE='common.account.status'"
#         List<HashMap<String, String>> list=DBUtil.getInstance().executeQuery(datasql)
#         for (HashMap<String, String> map : list) {
#             String item_cn=map.get("item_cn")
#             String item_value=map.get("item_value")
#
#             init.addComboValue("status", item_cn, item_value)
#         }
#
#         try {
#             SysTools.getInstance().printHtmlData(init.getJsonMap())
#         } catch (Exception e) {
#             e.printStackTrace()
#         }
#     }
#
#      # # # # # # # # # # # # # #数据处理
#      # 查询条件:product_name
#        search_product_name
#     public String getSearch_product_name(){
#         return search_product_name
#     }
#     public void setSearch_product_name(String value){
#         search_product_name=value
#     }
#
#      # 查询条件:manager_id
#        search_manager_id
#     public String getSearch_manager_id(){
#         return search_manager_id
#     }
#     public void setSearch_manager_id(String value){
#         search_manager_id=value
#     }
#
#      # 查询条件:size_
#        search_size_
#     public String getSearch_size_(){
#         return search_size_
#     }
#     public void setSearch_size_(String value){
#         search_size_=value
#     }
#
#      # 查询条件:status
#        search_status
#     public String getSearch_status(){
#         return search_status
#     }
#     public void setSearch_status(String value){
#         search_status=value
#     }
#
#      # 查询条件:create_date
#        search_create_date
#     public String getSearch_create_date(){
#         return search_create_date
#     }
#     public void setSearch_create_date(String value){
#         search_create_date=value
#     }
#
#      # 查询条件:trade_manager_id
#        search_trade_manager_id
#     public String getSearch_trade_manager_id(){
#         return search_trade_manager_id
#     }
#     public void setSearch_trade_manager_id(String value){
#         search_trade_manager_id=value
#     }
#
#      # 查询条件:accounting_id
#        search_accounting_id
#     public String getSearch_accounting_id(){
#         return search_accounting_id
#     }
#     public void setSearch_accounting_id(String value){
#         search_accounting_id=value
#     }
#
#      # 查询条件:risk_manager_id
#        search_risk_manager_id
#     public String getSearch_risk_manager_id(){
#         return search_risk_manager_id
#     }
#     public void setSearch_risk_manager_id(String value){
#         search_risk_manager_id=value
#     }
#
#      # 查询条件:transfer_id
#        search_transfer_id
#     public String getSearch_transfer_id(){
#         return search_transfer_id
#     }
#     public void setSearch_transfer_id(String value){
#         search_transfer_id=value
#     }
#
#      # 查询条件:sh_a_account
#        search_sh_a_account
#     public String getSearch_sh_a_account(){
#         return search_sh_a_account
#     }
#     public void setSearch_sh_a_account(String value){
#         search_sh_a_account=value
#     }
#
#      # 查询条件:sz_a_account
#        search_sz_a_account
#     public String getSearch_sz_a_account(){
#         return search_sz_a_account
#     }
#     public void setSearch_sz_a_account(String value){
#         search_sz_a_account=value
#     }
#
#      # 查询条件:money_account
#        search_money_account
#     public String getSearch_money_account(){
#         return search_money_account
#     }
#     public void setSearch_money_account(String value){
#         search_money_account=value
#     }
#
#      # 查询条件:account_passwd
#        search_account_passwd
#     public String getSearch_account_passwd(){
#         return search_account_passwd
#     }
#     public void setSearch_account_passwd(String value){
#         search_account_passwd=value
#     }
#
#      # 查询条件:fee_rate
#        search_fee_rate
#        roleEnglishName
#        user_id
#        user_name
#     public String getUser_name() {
#         return user_name
#     }
#
#     public void setUser_name(String user_name) {
#         this.user_name = user_name
#     }
#
#     public String getUser_id() {
#         return user_id
#     }
#
#     public void setUser_id(String user_id) {
#         this.user_id = user_id
#     }
#
#     public String getRoleEnglishName() {
#         return roleEnglishName
#     }
#
#     public void setRoleEnglishName(String roleEnglishName) {
#         this.roleEnglishName = roleEnglishName
#     }
#
#     public String getSearch_fee_rate(){
#         return search_fee_rate
#     }
#     public void setSearch_fee_rate(String value){
#         search_fee_rate=value
#     }
#
#   # 排序查询条件: sort
#        sort
#     public String getSort(){
#         return sort
#     }
#     public void setSort(String value){
#         sort=value
#     }
#
#      # 排序查询条件: order
#        order
#     public String getOrder(){
#         return order
#     }
#     public void setOrder(String value){
#         order=value
#     }
#      # 获取表格数据
sort=str()
order = str()
def queryListJson():

    logger.info(u"就是这么")
     # 当前页
    intPage = "1" if (page == None or page == "0") else page
     # 每页显示条数
    number = "10" if (rows == None or rows == "0") else rows
     # 每页的开始记录 第一页为1 第二页为number +1
     #int start = (intPage - 1) * number


     # 设置排序方式
    order_buffer= str()
    if(sort != ""):
        order_buffer+=" order by " + sort
    if(order != ""):
        order_buffer += " " + order

     #设置自己的查询条件
    buffer = str()
    if(search_product_name != ""):
        buffer += "where product_name like '%"+search_product_name+"%' and "
    if(len(buffer)>0):
        buffer = buffer[:-5] # 删除 and


     #获取总条数
    countsql="select count(*) from CM_PRODUCT_INFO"+buffer
    logger.info("queryListJson.countsql="+countsql)

    countstr=DBUtil.executeQueryList(countsql)
    countstr = countstr[0][0] if countstr else 0
     #获取具体数据
    datasql = "select t.product_id,t.product_name,find_user_name(t.manager_id) manager_id," \
              "find_user_name(t.trade_manager_id) trade_manager_id,find_user_name(t.accounting_id) accounting_id," \
              "find_user_name(t.risk_manager_id) risk_manager_id,find_user_name(t.transfer_id) transfer_id," \
              "t.size_,find_dict_name('common.account.status',t.status) status, t.create_date,t.sh_a_account,t.sz_a_account," \
              "t.money_account,t.account_passwd,t.fee_rate from CM_PRODUCT_INFO t"+buffer+ order_buffer
    datasql=DBUtil.getPageSql(datasql, int(intPage), int(rows))
    list=DBUtil.executeQueryMap(datasql)
    # list = list[0] if list else None
    res = {'total' : str(countstr), 'rows' : list}
    return res
    # Gson gson = SysTools.create()
    # HttpServletResponse response = ServletActionContext.getResponse()
    # response.setContentType("text/html charset=utf-8")
    # PrintWriter out = response.getWriter()
    # String jsonString = gson.toJson(list)
    # jsonString = "{\"total\":".concat(countstr)
    #         .concat(",\"rows\":").concat(jsonString).concat("}")
    # out.println(jsonString)
    # out.flush()
    # out.close()


# 获取表单数据
def loadData():
    print 'load Data'
    print 'product_id ' + str(product_id)
    if product_id:
        try:
            findobj = CmProductInfo.objects.get(product_id=product_id)
            print 'decode'
            print 'type',
            print type(findobj.product_name)
            print findobj.product_name
            # print findobj.product_name.decode('gbk')
            print 'return'
            return findobj
        except Exception, e:
            logger.error('loadData : %s', e)


#
#      #删除单行数据
#     public void deleteData() throws IOException {
#         boolean success = false
#
#         if (null != product_id) {
#
#             CmProductInfo obj = new CmProductInfo()
#             obj.setProduct_id(product_id)
#             this.defaultServiceDaoImpl.delete(obj)
#
#             success = true
#         }
#
#          try {
#             SysTools.getInstance().printHtmlData(success)
#          } catch (Exception e) {
#             logger.error("deleteData", e)
#          }
#     }
#


def saveData_x():
    print date
    print formobj.account_passwd
    print formobj.create_date
    print formobj.fee_rate
    print formobj.product_name
    print 'save --------------------date '
    return 'ok'

date = datetime.today()
#保存新建的表单数据
def saveData():

    """日期保存要成功脚本中必须出现秒
    """

    isModify = True if formobj.product_id else False
    resmap = {}
    try:
        formobj.create_date = date if type(date) is datetime else datetime.today()
        for key in formobj.__dict__:
            print key,
            print ' : ',
            print formobj.__dict__[key]
        if not isModify:
            formobj.product_id = CmProductInfo.objects.all().order_by('-product_id')[0].product_id + 1
            # 调用存储过程----产品的资产账户的创建（分配资产）

            # con = DBUtil.getInstance().getConnection()
            # cstmt = con.prepareCall("{?= call pkg_assert_manage.create_product_capital_account(?)}")
            # product_id = formobj.product_id
            # cstmt.registerOutParameter(1, Types.VARCHAR)
            # cstmt.setInt(2, product_id)
            # cstmt.execute()
            # String res1 = cstmt.getString(1)

            # res1 = DBUtil.executeUpdate("select pkg_assert_manage.create_product_capital_account(%s) from dual" % product_id)
            res1 = '99'
            logger.info("res1=" + res1)
        formobj.save()
        resmap.update(code='1', isModify=isModify)

    except Exception, e:
        logger.error("saveData : %s", e)
        resmap.update(code='0')
        resmap.update(msg="操作失败,原因:"+e.message)
    finally:

        #  DBUtil.getInstance().freeDBResource(null, cstmt, con)

        try:
            return resmap
        except Exception, e:
            logger.error("saveData : %s", e)


#
#      #获取添加相关人员的名单
#     public void getUserList() throws Exception{
#         logger.info("查询条件值="+roleEnglishName + "," + user_name)
#          #设置自己的查询条件
#         StringBuffer buffer=new StringBuffer()
#         if(!SysTools.isEmpty(user_name))
#             buffer.append(" and a.user_name like '%"+user_name+"%' ")
#
#         String sql = "select a.user_name,a.user_id from sm_usermessage a " +
#                 "where is_delete=0 " +
#                 "and a.user_id in (select userid from sm_user_role " +
#                 "where roleid = (select roleid from sm_roleinfo where roleen = '" + roleEnglishName + "'))" + buffer
#         logger.info(sql)
#         List list=DBUtil.getInstance().executeQuery(sql)
#
#          #获取总条数
#         String countsql="select count(*) from sm_usermessage a " +
#                 "where is_delete=0 and a.user_id " +
#                 "in (select userid from sm_user_role " +
#                 "where roleid = (select roleid from sm_roleinfo where roleen = '" + roleEnglishName + "'))" + buffer
#         logger.info("queryListJson.countsql="+countsql)
#         String countstr=DBUtil.getInstance().getValueFromSql(countsql)
#
#         Gson gson = SysTools.create()
#         HttpServletResponse response = ServletActionContext.getResponse()
#         response.setContentType("text/html charset=utf-8")
#         PrintWriter out = response.getWriter()
#         String jsonString = gson.toJson(list)
#          #SysTools.getInstance().printHtmlData(jsonString)
#         jsonString = "{\"total\":".concat(countstr)
#                 .concat(",\"rows\":").concat(jsonString).concat("}")
#         out.println(jsonString)
#         out.flush()
#         out.close()
#     }
#      #产品账户状态停止
#     public void updateStatusToPause() throws Exception{
#          #获取具体数据
#         if(!SysTools.isEmpty(search_value)){
#              #更新产品状态
#             String datasql = "update CM_PRODUCT_INFO set status='0' where product_id = "+search_value
#             logger.info(datasql)
#             DBUtil.getInstance().executeUpdate(datasql)
#              #更新产品相关投顾的状态
#             datasql = "update CM_INVEST_ACCOUNT_INFO set status = '0' where product_id = "+search_value
#             logger.info(datasql)
#             DBUtil.getInstance().executeUpdate(datasql)
#
#             SysTools.getInstance().printHtmlData(true)
#         }
#         else
#             SysTools.getInstance().printHtmlData(false)
#     }


'''
    comment：产品账户状态停止
    param : 传入的查询条件，productId
    return : Ture或False
    author : syc
'''
search_value = str()
def updateStatusToPause():
    productId = int(search_value)
    logger.info("查询条件值=%d" % productId)
    result = False

    if productId is not None:
        # 更新产品状态
        datasql = "update CM_PRODUCT_INFO set status='0' where product_id =%d" % productId
        logger.info('CM_PRODUCT_INFO表更新语句：'+datasql)
        productResult = DBUtil.executeUpdate(datasql)
        # 当产品状态成功更新后  1,None:sql语句执行失败,出现异常;2,-2:数据库连接失败导致执行失败
        if productResult is not None and productResult != -2:
            datasql = "update CM_INVEST_ACCOUNT_INFO set status = '0' where product_id = %d" % productId
            logger.info('CM_INVEST_ACCOUNT_INFO表更新语句：'+datasql)
            accountResult = DBUtil.executeUpdate(datasql)
            if accountResult is not None and accountResult != -2:
                result = True
    return result



      #产品账户状态激活
#     public void updateStatusToActive() throws Exception{
#          #获取具体数据
#         if(!SysTools.isEmpty(search_value)){
#              #更新产品状态
#             String datasql = "update CM_PRODUCT_INFO set status='1' where product_id = "+search_value
#             logger.info(datasql)
#             DBUtil.getInstance().executeUpdate(datasql)
#              #更新产品相关投顾的状态
#             datasql = "update CM_INVEST_ACCOUNT_INFO set status = '1' where product_id = "+search_value
#             logger.info(datasql)
#             DBUtil.getInstance().executeUpdate(datasql)
#
#             SysTools.getInstance().printHtmlData(true)
#         }
#         else
#             SysTools.getInstance().printHtmlData(false)
#     }
# }

'''
    comment：产品账户状态激活
    param : 传入的查询条件，productId
    return : Ture或False
    author : syc
'''
def updateStatusToActive():
    productId = int(search_value)
    logger.info("查询条件值=%d" % productId)
    result = False

    if productId is not None:
        # 更新产品状态
        datasql = "update CM_PRODUCT_INFO set status='1' where product_id=%d" % productId
        logger.info('CM_PRODUCT_INFO表更新语句：'+datasql)
        productResult = DBUtil.executeUpdate(datasql)
        # 当产品状态成功更新后  1,None:sql语句执行失败,出现异常;2,-2:数据库连接失败导致执行失败
        if productResult is not None and productResult != -2:
            datasql = "update CM_INVEST_ACCOUNT_INFO set status = '1' where product_id = %d" % productId
            logger.info('CM_INVEST_ACCOUNT_INFO表更新语句：'+datasql)
            accountResult = DBUtil.executeUpdate(datasql)
            if accountResult is not None and accountResult != -2:
                result = True
    return result
